#include "spi3.h"

void vSpiSoftDelay(void)
{
 #if (FIFO_DLY_VAL==0)
	return;
 #else
 	unsigned char i;
	for(i=FIFO_DLY_VAL; i!=0; i-- )
		asm("nop");
 #endif
}

//*********************************************************
//														   
//*********************************************************
void vSpiInit(void)
{

}

void vSpiWriteByte(unsigned char dat)
{
 unsigned char i;
 
	SCK   = 0;
	nCSB  = 0;
   // vSpiSoftDelay();
	for(i=8; i!=0; i--)
 	{
		SCK = 0;
		if(dat&0x80)
			SDA = 1;
		else
			SDA = 0;
		SCK = 1;
		dat <<= 1;	
 	} 
	SCK = 0;
//	vSpiSoftDelay();
	SDA = 1;
 return;
}

unsigned char bSpiReadByte(void)
{
 unsigned char rdPara = 0;
 unsigned char i;
 
// __DRV_SFR_PageIndex(0);
 //P1M1 |= P1M15;
 TRISA = 0B00010000;
 SCK = 0;
 SDA = 1;
 nCSB = 0;
 
 for(i=8; i!=0; i--)
 	{
 	SCK = 1;
 	rdPara <<= 1;
 	if(SDA)	
 		rdPara |= 0x01;
 	else
 		rdPara |= 0x00;
 	SCK = 0;
 	}
 TRISA = 0B00000000;

 //__DRV_SFR_PageIndex(0);
// P1M1 &= (~P1M15);
 SDA = 1;

 return(rdPara);
}

void vSpiWrite(unsigned int dat)
{
	
 vSpiWriteByte((unsigned char)(dat>>8)&0x7F);	
 vSpiWriteByte((unsigned char)dat);
 nCSB = 1;
}

void vSpiSendCmd(unsigned char cmd_val)
{
 vSpiWriteByte(cmd_val&0x7F);
 nCSB = 1;
}

unsigned char bSpiRead(unsigned char addr)
{
 unsigned char dat;	
 	SCK   = 0;
	nCSB  = 0;
    vSpiSoftDelay();
	 vSpiWriteByte(addr|0x80);
	 dat = bSpiReadByte();
	 vSpiSoftDelay();
	 SDA  = 1;
	 SCK=0;
	 nCSB = 1;
 return(dat);
}

void vSpiBurstWrite(unsigned char spi_adr, unsigned char ptr[], unsigned char length)
{
 unsigned char i;

 vSpiWriteByte(spi_adr&0x7F); 
 for(i=0; i<length; i++)
 	vSpiWriteByte(ptr[i]);
 SDA  = 1; 		
 nCSB = 1;
}

void vSpiBurstRead(unsigned char spi_adr, unsigned char ptr[], unsigned char length)
{
 unsigned char i;

 vSpiWriteByte(spi_adr|0x80); 
 for(i=0; i<length; i++)
 	ptr[i] = bSpiReadByte();	
 SDA  = 1;
 nCSB = 1;
}


void vSpiWriteFifo(unsigned char dat)
{
 unsigned char i;
 
 nFCSB = 0;
 for(i=8; i!=0; i--)
 	{
 	SCK = 0;
 	if(dat&0x80)
 		SDA = 1;
 	else
 		SDA = 0;
 	SCK = 1;
 	dat <<= 1;	
 	} 

 SCK   = 0;
 nFCSB = 1;
 SDA   = 1;
 vSpiSoftDelay(); 
 return;	
}

unsigned char bSpiReadFifo(void)
{
 unsigned char rdPara = 0;
 unsigned char i;

 //__DRV_SFR_PageIndex(0);
 //P1M1 |= P1M15;
   TRISA = 0B00010000; 
 SDA   = 1;
 nFCSB = 0;
 
 for(i=8; i!=0; i--)
 	{
 	SCK = 1;
 	rdPara <<= 1;
 	if(SDA)	
 		rdPara |= 0x01;
 	else
 		rdPara |= 0x00;
 	SCK = 0;
 	}

 nFCSB = 1;	
 TRISA = 0B00000000;
 //__DRV_SFR_PageIndex(0);
 //P1M1 &= (~P1M15); 	
 SDA   = 1;	

 vSpiSoftDelay();
 return(rdPara);
}

void vSpiBurstWriteFifo(unsigned char ptr[], unsigned char length)
{
 unsigned char i;

 if(length!=0)
 	{
	for(i=0; i<length; i++)
	{
		vSpiWriteFifo(ptr[i]);
		asm("clrwdt");
	}
	}
 return;
}

void vSpiBurstReadFifo(unsigned char ptr[], unsigned char length)
{
 unsigned char i;

 if(length!=0)
 	{
	for(i=0; i<length; i++)
		ptr[i] = bSpiReadFifo();
	}
 return;
}


